from Accounting.CashFlow.Base import *
from Accounting.CashFlow.SubRed import *
from Accounting.Entity.Utils import *
from DataAccess.DBConnFactory import DBConnFactory


class Fee(CashFlow):
	db_table = "fee"
	
	def __init__(self, ref_date, curncy, is_payment_date, is_redem, entity): 
		CashFlow.__init__(self, ref_date, None, curncy, entity)
		self.is_payment_date = True if is_payment_date=='T' else False
		self.is_redem = True if is_redem=='T' else False
		
	def type(self):
		raise NotImplementedError
		
	def category(self):
		raise NotImplementedError
	
	def calculate(self):
		raise NotImplementedError
		
	def persistence(self):
		if abs(self.amount())<0.001:
			return
		
		conn = DBConnFactory().get_db_connection('ACCOUNTING')		
		#if not self.amount():
		#	print 'debug,', self.ref_date.isoformat(), self.type() 

		sql_text = '''insert into fee 
					(ref_date,entity,subtype,amount,curncy)
					values(TO_DATE(:1,'yyyy-mm-dd'),:2,:3,:4,:5)'''
		conn.cursor().execute(sql_text, (self.ref_date.isoformat(), 
										self.entity.get_entity_id(),
										self.type(), 
										self.amount(), 
										self.currency()))
		conn.commit()
			
	#def pay_amount(self):
	#	if self.is_payment_date:
	#		return self.amount()
	#	else:
	#		return 0
	
	def is_pay_date(self):
		return self.is_payment_date
		
	def cash_redeming(self): 
		return self.is_redem
		
		
	def trigger_fund_share_chg(self, ref_date):		
		if not self.is_pay_date():
			return []
		
		ret = []
		curncy = self.currency()
		amount = self.amount()
		
		if self.cash_redeming():
			conv_by = share_amt_conv_type(ref_date, self.entity)

			if amount > 0:
				#print 'debug, Redemption=', amount
				corr_sub_id = query_first_subscription_id(self.entity.get_parent(), self.entity)
				act = Redemption(ref_date, amount, curncy, RedemptionByAmount, 
								corr_sub_id, conv_by, self.entity, self.type())
				ret.append(act)	
			elif amount < 0:
				#print 'debug, Subscription=', amount,self.entity,self.type(),self.__class__
				act = Subscription(ref_date, -1*amount, curncy, conv_by, self.entity, self.type())				
				ret.append(act)
			else:
				pass
		
		return ret